// 安全监控系统 编辑模式下 断电区域相关功能的组件

import component from "../Component.js"
import zTreeUtils from "../../experience/utils/zTreeUtils.js";
import {LayerType} from "../../experience/db/SafeMonitorType.js"
const Overlay = ol.Overlay;
const Draw = ol.interaction.Draw;
const Collection = ol.Collection;
export default class PoweredAreaEdit extends component {
    constructor() {
        super()
    }

    async control() {
        this.ztreeUtils = new zTreeUtils()
        this.drawAreaInteraction = null
        this.AreaFeatures = new Collection([])
        // 当前选中的 传感器id
        this.currentSelectGas = null
        // 当前选中的 断电区域
        this.PAarea = null
        const DrawArea = $('#pAreaDraw')
        const PointArea = $('#pAreaPoint')
        // 创建 用于 编辑断电区域的 overlay
        const OverlayContainer = document.getElementById('PoweredAreaContainer')
        this.PoweredAreaOverlay = new Overlay({ element: OverlayContainer,autoPan:true,positioning:'center-center' })
        this.drawer.map.addOverlay(this.PoweredAreaOverlay);
        // 创建断电区域的对话框
        this.PAdialog = this.CreatePaDialog()
        // 获取所有 断馈电传感器的列表
        const {data:gasNodes} = await this.ztreeUtils.getAllGasNodes()
        const PoweredGasNodes = gasNodes.filter((node) => {
            return node.node_type == '断馈电'
        })
        // 存储 断馈电 传感器列表
        this.PoweredGasNodes = PoweredGasNodes
        // 绑定 点击 绘制断电区域的事件回调函数
        DrawArea.on('click',async (e) => {

            const color = DrawArea.css('color')
            // 未激活状态
            if(color == 'rgb(51, 51, 51)') {
                // 1.颜色的切换
                DrawArea.css({'color':'rgb(255,0,0)'})
                // 2.打开绘图交互
                this.drawAreaInteraction = new Draw({
                    source:this.drawer.source(LayerType.SMPoweredArea),
                    type:'Polygon',
                    features:this.AreaFeatures
                })
                this.drawer.map.addInteraction(this.drawAreaInteraction)
            }
            // 激活状态
            else {
                // 1.颜色的切换
                DrawArea.css({'color':'rgb(51,51,51)'})
                // 2.存储 断电区域
                const AreaFeatures = this.AreaFeatures.getArray()
                const AreaCoordinates = []
                AreaFeatures.forEach((feature) => {
                    const coordinates = feature.getGeometry().getCoordinates()[0]
                    AreaCoordinates.push(coordinates)
                })
                const unNormalAreaCoordinates = AreaCoordinates.map((area) => {
                    const resArr = []
                    area.forEach((el) => {
                        resArr.push([this.algo.denormalX(el[0]),this.algo.denormalY(el[1])])
                    })
                    return resArr

                })
                await this.api.addSmPoweredAreas(unNormalAreaCoordinates)
                // 3.关闭 draw交互,并清空 modify图层
                this.drawer.map.removeInteraction(this.drawAreaInteraction)
                this.drawer.source(LayerType.Modify).clear()
                // 4.更新 断电区域的图层
                this.drawer._smpoweredarea()
                // 5.清空 this.AreaFeatures
                this.AreaFeatures = new Collection([])

            }

        })
        this.emitter.on('send-powered-area',() => {
            const powered_area_feature = this.emitter.params[0]
            // 在断电区域选择器激活的状态下  要执行的进行响应的函数
            this.SelectPAReflect(powered_area_feature)
        })
        // 绑定 点击 选中断电区域的事件回调函数
        PointArea.on('click',(e) => {
            // 1.颜色的切换
            const color = PointArea.css('color')
            // 未激活状态
            if(color == 'rgb(51, 51, 51)') {
                PointArea.css({'color':'rgb(255,0,0)'})
                localStorage.setItem('PA_select_status',true)
            }
            // 激活状态
            else {
                PointArea.css({'color':'rgb(51,51,51)'})
                localStorage.setItem('PA_select_status',false)
                // 清除 overlay
                this.PoweredAreaOverlay.setPosition(undefined)
            }
        })
        // 绑定 断电区域的设置和删除按钮
        $('#pa_edit_button').on('click',(e) => {
            // 1.首先触发 弹窗，弹窗的功能是去将该断电区域与相关的传感器进行关联。
            this.PAdialog.open()
            // 2. 将弹窗内部的select标签内的option 根据请求得到的传感器列表 进行更新
            let optionHtml = ''
            this.PoweredGasNodes.forEach((gas) => {
                optionHtml+=`<option value="${gas.node_id}">${gas.name}</option>`
            })
            if(this.PoweredGasNodes.length > 0) {
                // 当前选中的 断馈电传感器
                this.currentSelectGas = this.PoweredGasNodes[0].node_id
            }
            const selector = $('#SensorSelector')
            selector[0].innerHTML = optionHtml
            selector.on('change',(e) => {
                this.currentSelectGas = e.target.value
            })
        })
        $('#pa_delete_button').on('click',(e) => {
            this.app.dialog.confirm('确定删除区域？',() => {
                this.DeletePoweredArea()
            })
        })


    }

    template() {
        const PAoverlay = `<div id="PoweredAreaContainer">
                                <button id="pa_edit_button" class="PoweredAreaInnerButton PAInnerEditButton">设置</button>
                                <button id="pa_delete_button" class="PoweredAreaInnerButton PAInnerDeleteButton">删除</button>
                            </div>`
        const PAdialog = `<div id="PoweredAreaDialog" style="width: 400px;height: 400px;background-color: red">
                               
                            </div>`
        this.$$("#article").append(PAoverlay);
        this.$$("#article").append(PAdialog);
    }

    SelectPAReflect(PA_feature) {
        const PolygonCoordinates = PA_feature.getGeometry().getCoordinates()
        // 计算 polygon的中心坐标
        const center = this.ComputePolygonCenterPosition(PolygonCoordinates[0])
        this.PoweredAreaOverlay.setPosition(center)
        this.PAarea = PA_feature.get('id')
    }
    // 计算多边形的相对
    ComputePolygonCenterPosition(PolygonCoordinates) {
        const extent = ol.extent.boundingExtent(PolygonCoordinates); //获取一个坐标数组的边界，格式为[minx,miny,maxx,maxy]
        const center = ol.extent.getCenter(extent);   //获取边界区域的中心位置
        return center
    }
    // 创建 断电区域的dialog
    CreatePaDialog() {
        const dialog = this.app.dialog.create({
            title:'关联断电馈电传感器',
            cssClass:'PAdialog',
            content: `
                    <div class="PaDialogInnerBox">
                        <select id="SensorSelector" style="width: 100%;height: 30px;margin: 5px auto;">
                            <option value="default" selected>从列表中选择</option>
                        <select/>
                    </div>
                    `,
            buttons: [{
                text: '关闭'
            }, {
                text: '保存',
                onClick: async () => {
                    this.submitPoweredAreaRelation()
                }
            }],

        })
        return dialog
    }

    // 点击 保存按钮
    async submitPoweredAreaRelation() {
        await this.api.updateSmPoweredArea(this.PAarea,this.currentSelectGas)
    }
    // 删除 区域
    async DeletePoweredArea() {
        await this.api.deleteSmPoweredArea(this.PAarea)
        // 重置 断电区域的overlay
        this.PoweredAreaOverlay.setPosition(undefined)
        // 更新 断电区域的图层
        this.drawer._smpoweredarea()
    }

}

